/*
 * @Author: sean_kei@163.com
 * @Date: 2021-11-12 09:52:56
 * @LastEditors: sean_kei@163.com
 * @LastEditTime: 2021-12-01 16:57:36
 */
package com.wxhandle.cleandemo.sso.entity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.wxhandle.cleandemo.core.domain.identity.SysUser;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import lombok.Data;

@Data
public class CarbonUser implements UserDetails{

    Long id;

    String name;

    String pwd;

    boolean enabled;

    String unionId;

    String[] roles;

    public static CarbonUser of(SysUser user){
        CarbonUser cb = new CarbonUser();
        cb.id = user.getId();
        cb.name = user.getName();
        cb.pwd = user.getPwd();
        cb.roles = user.getRoles().stream().map(role->role.getId()).toArray(String[]::new);
        cb.enabled = true;
        //为了返回一个UserDetails 使用User
        return cb;
    }
    public static CarbonUser of(User user){
        CarbonUser cb = new CarbonUser();
        cb.name = user.getUsername();
        cb.pwd = user.getPassword();
        cb.roles = user.getAuthorities().stream().map(role->role.getAuthority()).toArray(String[]::new);
        cb.enabled = true;
        return cb;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities=new ArrayList<>();
        for (String role:roles) {
            //循环一次,就拿到了表格权限,使用authority字段
            GrantedAuthority authority= new SimpleGrantedAuthority(role);
            authorities.add(authority);
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return pwd;
    }

    @Override
    public String getUsername() {
        return name;
    }

	public void setUsername(String username) {
		this.name = username;
	}

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
    
}
